package com.mission.datasave

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.mission.datasave.databinding.ActivitySharedpreferencesBinding

/**
 * Created by KevenTao on 1/9/21.
 */
class SharedPreferencesActivity : AppCompatActivity() {

    private lateinit var mBinding: ActivitySharedpreferencesBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivitySharedpreferencesBinding.inflate(layoutInflater)

        setContentView(mBinding.root)

        mBinding.saveBtn.setOnClickListener {
//            putData()
            putDataQuick()
        }

        mBinding.getBtn.setOnClickListener {
            getData()
        }
    }

    /**
     * 存储数据
     */
    private fun putData() {
        val sp = getSharedPreferences("data_sp", Context.MODE_PRIVATE)
        val edit = sp.edit()
        edit.putBoolean("boolean", true)
        edit.putString("string_sp_1", "哈哈哈，这是存储String的")
        edit.apply()
    }

    /**
     * 通过扩展函数存储数据
     */
    private fun putDataQuick() {
        getSharedPreferences("data_sp", Context.MODE_PRIVATE).open {
            putString("string1", "我啦哈哈")
            putString("string2", "看看看吧吧v")
        }
    }

    /**
     * 读取数据
     */
    private fun getData() {
        val sp = getSharedPreferences("data_sp", Context.MODE_PRIVATE)
        Log.e(
            "mission",
//            "String is ${sp.getString("string_sp_1", "")},Boolean is ${sp.getBoolean(
//                "boolean",
//                false
//            )
            "String1 is ${sp.getString("string1", "")},String2 is ${sp.getString(
                "string2",
                ""
            )}"
        )
    }

    companion object {
        @JvmStatic
        fun start(context: Context) {
            val intent = Intent(context, SharedPreferencesActivity::class.java)
            context.startActivity(intent)
        }
    }
}